<!-- demoPage -->
<template>
  <div class="demo-page" ref="demo">
    <div class="search">
      <el-form class="search-form" ref="queryForm" :model="queryFormData" label-width="120px">
        <div class="form-left">
          <el-row>
            <el-col :span="6" v-for="(item, index) of queryFormSelectArr" :key="item.level">
              <el-form-item :label="positionMap[item.level]">
                <el-select v-model="queryFormData[item.level]" :placeholder="'请选择' + positionMap[item.level]" clearable
                  @clear="clearCurrentSelect(index)">
                  <el-option v-for="selectItem of item.selectList" :key="selectItem" :label="selectItem"
                    @click.native="selectChange(index)" :value="selectItem" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否空房">
                <el-select v-model="queryFormData.isEmpty" clearable size="small">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-right">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </div>
      </el-form>
    </div>
    <mc-button ref="mcButton" :quickButtons="quickButtons" @buttonsEvent="buttonsEvent"></mc-button>
    <mc-table ref="McTable" :labels="tableLabels" :data="tableData" :settings="tableSettings"
      @current-change="currentChange" @selection-change="selectionChange">
      <template v-slot:index>
        <el-table-column label="序号" align="center" header-align="center">
          <template slot-scope="scope">
            {{ (page["page-size"] * (page["current-page"] - 1)) + scope.row.index }}
          </template>
        </el-table-column>
      </template>
      <template v-slot:scope>
        <el-table-column label="网格区域" align="center" header-align="center">
          <template slot-scope="scope">
            <el-link type="primary">{{ scope.row.region || "暂无" }}</el-link>
          </template>
        </el-table-column>
      </template>
      <template v-slot:handle>
        <el-table-column label="操作" align="center" header-align="center">
          <template slot-scope="scope">
            <el-button type="text" :disabled="!!scope.row.isEmpty" size="small" @click="lookHandle(scope.row)">{{
                !scope.row.isEmpty ? "住户信息" : "空户"
            }}</el-button>
            <el-button v-if="scope.row.isEmpty" type="text" @click="deleteEmpty(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </mc-table>
    <mc-pager ref="McPager" v-if="pager" :settings="page" @current-change="getTableData" @size-change="sizeChange">
    </mc-pager>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog" width="700px">
      <el-table :data="tableDataDalog" style="width: 100%">
        <el-table-column prop="name" label="姓名"> </el-table-column>
        <el-table-column prop="sex" label="性别">
          <template slot-scope="{row}">
            {{ row.sex == '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="householdRelation" label="身份">
        </el-table-column>
        <el-table-column prop="age" label="年龄"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">退出</el-button>
        <!-- <el-button type="primary" @click="submitDialog">确 定</el-button> -->
      </span>
    </el-dialog>
    <el-dialog title="上传" :visible.sync="showDialogUpload" width="696px" height="40%" :close-on-click-modal="false">
      <div class="dialog-note dialog-note-form">
        <div class="form">
          <div class="container-from">
            <!-- 
              :headers="uploadToken"
            -->
            <el-row>
              <el-col :span="12">
                <el-upload class="upload-demo" action="/api/lh-community-web/house/manage/upload" :limit="5"
                  :file-list="fileList" :on-success="onUploadSuccess" :before-upload="onBeforeUpload"
                  :on-error="onUploadError" :show-file-list="true">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传xls/xlsx文件，且不超过10M
                  </div>
                </el-upload>
              </el-col>
              <el-col :span="12">
                <el-button size="small" type="success" @click="templateDownload">下载模板</el-button>
              </el-col>
            </el-row>
            <!-- <el-progress
              v-if="progressFlag"
              :percentage="progressUpload"
            ></el-progress> -->
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog ref="dialog2" :title="dialog2Title" :visible.sync="dialog2Visible" :before-close="dialog2Close"
      width="750px">
      <template v-if="dialog2Visible">
        <mc-form ref="updateForm" @emitFormData="emitFormData" idx="0" :labels="form2Labels" :data="form2Data"
          :rules="form2Rules" :settings="form2Settings" v-bind="$attrs">
          <template #split="{ info }">
            <el-divider><i :class="'el-icon-' + info.icon" style="margin-right: 5px;"></i>{{ info.name }}</el-divider>
          </template>
          <template #houseNumber>
            <el-row type="flex" :gutter="20" class="fit-el-row">
              <el-col v-for="(house, index) in form2Data.houseNumbers" :span="12">
                <el-form-item :label="'房间号' + (index + 1)" :key="house.key" labelWidth="90px"
                  :prop="'houseNumbers.' + index + '.value'" :rules="form2Rules.houseNumbers">
                  <div class="form2-data">
                    <el-input v-model="house.value"></el-input>
                    <el-button @click.prevent="removeHouse(index)">删除</el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-button @click="addHouse">新增房间号</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </mc-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog2Close">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import McButton from "@/basePackage/McButton";
import McTable from "@/basePackage/McTable";
import McPager from "@/basePackage/McPager";

import McForm from "@/components/Form/index.vue";
import { debounce } from "../../common/utils";

import {
  getHouseList,
  getHouseInfoByHouseId,
  getHouseSelectInfoBySearch,
  deleteHouseByHouseIds,
  addHouseInfo
} from "../../api/home";


export default {
  data() {
    const positionMap = {
      communityName: '所在小区',
      building: '所在楼栋',
      unit: '单元号',
      houseNumber: '房间号',
      houseNumbers: '房间号',
    }
    var validateNumber = (rule, value, callback) => {
      if (value == '') callback()
      if (!/^\d{1,5}$/.test(value)) {
        callback(new Error(`请输入正确的数字格式`));
      } else {
        callback();
      }
    };
    return {
      //本地存储key
      storageKey: "demo",
      // 查询
      queryFormData: {
        building: null,
        isEmpty: null,
        region: null,
        unit: null,
        pageNum: 1,
        pageSize: 20,
      },
      // 小区名称映射表
      positionMap,
      // 小区名 列表 
      queryFormSelectArr: [],
      pager: true,
      page: {
        "current-page": 1,
        "page-size": 20,
        "page-sizes": [20, 50, 100],
        total: 0,
        background: true,
      },
      total: 0,
      quickButtons: ["import", "export", 'add', 'delete'],
      showDialogUpload: false,
      fileList: [],

      tableDataDalog: [],
      tableLabels: [
        {
          label: "序号",
          slotName: "index",
        },
        {
          label: '小区',
          prop: 'communityName',
          type: 'string'
        },
        // {
        //   label: "网格区域",
        //   prop: "region",
        //   type: "string",
        //   slotName: "scope",
        // },
        {
          label: "楼幢",
          prop: "building",
          type: "string",
        },
        {
          label: "单元号",
          prop: "unit",
          type: "string",
        },
        {
          label: "房间号",
          prop: "houseNumber",
          type: "string",
        },
        {
          label: "操作",
          prop: "op",
          slotName: "handle",
        },
      ],
      //假数据请务必设置唯一id
      tableData: [],
      // houseSelectInfo: [],
      tableSettings: {
        attrs: {
          loading: false,
          selectable: true
        },
      },
      selectRowArr: [],
      showDialog: false,
      dialogTitle: "住户信息",

      // 新增房屋信息
      form2Data: {
        communityName: '',
        building: '',
        region: '',
        unit: '',
        houseNumbers: [
          {
            value: ''
          }
        ],
      },
      dialog2Visible: false,
      dialog2Title: '',
      form2Labels: [
        {
          info: {
            name: '基本信息',
            icon: 'mobile-phone'
          },
          colNum: 24,
          slotName: 'split',
        }, {
          label: '所在小区',
          prop: 'communityName',
          type: 'string',
          colNum: 12,
        }, {
          label: '所在楼栋',
          prop: 'building',
          type: 'string',
          colNum: 12,
        }, {
          label: '所在区域',
          prop: 'region',
          type: 'string',
          colNum: 12,
        }, {
          label: '所在单元',
          prop: 'unit',
          type: 'string',
          colNum: 12,
        },
        {
          info: {
            name: '房间信息',
            icon: 's-home'
          },
          colNum: 24,
          slotName: 'split',
        },
        {
          label: '房间号',
          slotName: 'houseNumber',
          colNum: 24,
        }],
      form2Settings: {
        attrs: {
          layout: true,
        },
        itemAttrs: {
          "label-width": "90px",
        },
      },
      form2Rules: {
        communityName: [
          {
            message: "请输入所在小区",
            required: true,
            trigger: "blur",
          }
        ],
        unit: [
          { validator: validateNumber, trigger: "blur" },
        ],
        building: [
          { validator: validateNumber, trigger: "blur" },
        ],
        houseNumbers: [
          { validator: validateNumber, trigger: "blur" },
          {
            message: "请输入房间号",
            required: true,
            trigger: "blur",
          }
        ]
      },
      eventStatus: "",

      row: {},
    };
  },

  components: {
    McButton,
    McTable,
    McPager,
    McForm
  },

  computed: {
    debounceHandleSearch() {
      return debounce(this.handleQuery, 700);
    },
  },

  mounted() {
    // 这个options 就是所有项目中, 所有对于不一样的东西进行
    this.pageInit();
    this.calcTableHeight();
  },

  methods: {
    /**计算表格高度 */
    calcTableHeight() {
      let vm = this;
      vm.$nextTick(() => {
        let buttonHeight = 0;
        if (vm.$refs.mcButton && vm.$refs.mcButton.$el.offsetHeight) {
          buttonHeight = vm.$refs.mcButton.$el.offsetHeight;
        }
        this.$refs.mcTable.setTableAttr(
          "height",
          vm.$refs.demo.offsetHeight - buttonHeight - 20
        );
      });
    },
    pageInit() {
      this.getHouseList();
      this.getHouseSelectInfo();
    },
    /**获取表格数据 */
    getTableData(val) {
      this.queryFormData.pageNum = val;
      this.getHouseList();
    },
    sizeChange(val) {
      //val返回条目数
      this.page["page-size"] = val;
      this.queryFormData.pageSize = val;
      this.getHouseList();

    },

    resetQuery() {
      this.queryFormData = {
        name: null,
        building: null,
        communityName: null,
        pageNum: 1,
        pageSize: 20,
      };
      this.$refs.queryForm.resetFields();
    },
    getHouseList() {
      // 获取用户列表
      getHouseList(this.queryFormData).then(res => {
        this.tableData = res.records;
        this.page.total = Number(res.total);
        this.page["current-page"] = res.current;
        this.ableDataAddIndex()
      })
    },
    selectChange(currentIndex) {
      // 如果选择了 前面的选择框
      if (currentIndex + 1 < this.queryFormSelectArr.length) {
        // 将 queryFormSelectArr 改变到合适的大小
        let tempArr = this.queryFormSelectArr.splice(currentIndex + 1, Infinity)
        // 将 绑定的数据 更改为正确的值
        for (let item of tempArr) {
          this.queryFormData[item.level] = ''
        }
      }
      this.getHouseSelectInfo()
    },
    clearCurrentSelect(currentIndex) {
      if (currentIndex + 1 < this.queryFormSelectArr.length) {
        // 将 queryFormSelectArr 改变到合适的大小
        let tempArr = this.queryFormSelectArr.splice(currentIndex + 1, Infinity)
        // 将 绑定的数据 更改为正确的值
        for (let item of tempArr) {
          this.queryFormData[item.level] = ''
        }
      }
    },
    ableDataAddIndex() {
      for (let i = 1; i <= this.tableData.length; i++) {
        this.tableData[i - 1].index = i
      }
    },
    deleteEmpty(info) {
      this.$confirm("是否确定删除此条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.deleteHouseByHouseIds(info.id)
      });
    },
    deleteHouseByHouseIds(info) {
      deleteHouseByHouseIds(info).then(res => {
        if (res.code == 200) {
          this.getHouseList()
          this.$message.success("删除成功！");
        } else {
          this.$message.error(res.message);
        }
      })
    },
    // 注意这个方法, 请求参数不一样,获取到不一样的数据
    getHouseSelectInfo() {
      // 动态获取select数据
      getHouseSelectInfoBySearch(this.queryFormData).then(res => {
        if (res.data.level == 'houseNumber') return
        this.queryFormSelectArr.push(res.data)
      })
    },
    // 住户信息
    async lookHandle(info) {
      this.showDialog = true;
      // console.log(info.id)
      let res = await getHouseInfoByHouseId(info.id);
      // console.log(res);
      this.tableDataDalog = res.data;
    },
    onUpload() {
      this.progressFlag = false;
      this.fileList = [];
      this.showDialogUpload = true;
    },
    onUploadSuccess(response, file, fileList) {
      this.progressUpload = 100;
      clearInterval(this.timer);
      if (response.code === 100) {
        this.fileList = [];
        this.onLoadList();
        this.$message.success("上传成功");
        this.showDialogUpload = false;
      }
    },
    onUploadError(err, file, fileList) {
      this.$message.error("上传失败");
    },
    onBeforeUpload(file) {
      let excelist = ["xls", "xlsx"];
      let flieArr = file.name.split(".");
      let fileSuffix = flieArr[flieArr.length - 1];
      let result = excelist.some(function (item) {
        return item == fileSuffix;
      });
      let flag = file.size < 1024 * 1024 * 10 && result;
      if (!flag) {
        this.$message.error("只能上传xls/xlsx文件，且不超过10M");
      } else {
        this.progressFlag = true;
        this.progressUpload = 0;
        this.timer = setInterval(() => {
          if (this.progressUpload < 98) {
            this.progressUpload++;
          }
        }, 200);
      }

      return flag;
    },
    getCookie(name) {
      var strcookie = document.cookie;
      var arrcookie = strcookie.split("; ");
      for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] === name) {
          return arr[1];
        }
      }
      return "";
    },

    templateDownload() {
      // window.open("http://10.10.77.104:8001/person/manage/download/example");
      window.open("/api/lh-community-web/house/manage/download/example");
    },
    //按钮回调
    buttonsEvent(val) {
      this.eventStatus = val.value;
      switch (val.value) {
        case "add": {
          this.dialog2Title = '添加房屋信息'
          this.dialog2Visible = true
          // console.log(this.$options.data().form2Data)
          this.form2Data = this.$options.data().form2Data
          break
        }
        case 'delete':
          {
            this.$confirm("是否确定删除这些数据吗?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              let arr = this.selectRowArr.map(item => item.id)
              this.deleteHouseByHouseIds(arr)
            });
            break
          }
        case "export":
          {
            window.open("/api/lh-community-web/house/manage/export");
            break;
          }
        case "import":
          {
            this.onUpload();
            break;
          }
      }
    },
    handleQuery() {
      this.queryFormData.pageNum = 1;
      this.getHouseList();
    },
    addHouse() {
      this.form2Data.houseNumbers.push({
        value: ''
      })
    },
    removeHouse(houseIndex) {
      if (this.form2Data.houseNumbers.length == 1) {
        return
      }
      this.form2Data.houseNumbers.splice(houseIndex, 1)
    },
    //提交表单
    submitDialog() {
      // this.tableSettings.attrs.loading = true;
      let flag = true;
      try {
        this.$refs.updateForm.checkForm();
      } catch (error) {
        flag = false;
      }
      if (flag) {
        if (this.eventStatus == "add") {
          // this.tableSettings.attrs.loading = false;
          let tempHouseData = { ...this.form2Data }
          if (this.form2Data.houseNumbers.length > 1) {
            tempHouseData.houseNumbers = this.form2Data.houseNumbers.reduce((a, b) => {
              if (typeof a == 'object') {
                a = a.value
              }
              return a + ',' + b.value
            })
          } else {
            tempHouseData.houseNumbers = this.form2Data.houseNumbers[0].value
          }
          addHouseInfo(tempHouseData).then(res => {
            if (res.status) {
              this.dialog2Close()
              this.getHouseList()
              this.$message.success("新增成功！");
            } else {
              this.$message.error(res.message);
            }
          })
        }
      }
      // if (this.eventStatus == "edit") {
      //   this.$message.success("修改成功！");
      // }
    },
    dialog2Close() {
      this.dialog2Visible = false
    },
    emitFormData(data) {
      console.log(data)
    },
    /**计算表格高度 */
    calcTableHeight() {
      let vm = this;
      vm.$nextTick(() => {
        let pagerHeight = 0;
        if (vm.$refs.McPager && vm.$refs.McPager.$el.offsetHeight) {
          pagerHeight = vm.$refs.McPager.$el.offsetHeight;
        }
        this.$refs.McTable.setTableAttr(
          "height",
          vm.$refs.demo.offsetHeight - pagerHeight - 100
        );
      });
    },
    //获取当前选中行
    currentChange(row) {
      this.row = row;
      this.$refs.mcButton.changeButtonState(
        ["edit", "delete"],
        "disabled",
        false
      );
    },
    selectionChange(rows) {
      this.selectRowArr = rows
    }
  },
};
</script>

<style lang="scss" scoped>
.demo-page {
  width: 100%;
  height: 100%;
}

.search-form {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .form-left {
    flex: 1;
    margin-right: 30px;
  }

  .form-right {
    width: 200px;
  }
}

.form2-data {
  display: flex;
}
</style>